using ViScript.Core.Utils;

namespace ViScript.Core.Utils
{
    public class TextFactory : ITextFactory
    {
        private readonly IEscapeStrategy escapeStrategy;

        public TextFactory(IEscapeStrategy escapeStrategy)
        {
            this.escapeStrategy = escapeStrategy;
        }

        public IText CreateText(string text)
        {
            string trimmedText = text.Trim(Sentence.SEPARATORS);
            if (IsQutoed(trimmedText))
            {
                trimmedText = trimmedText.Trim('"', '\'');
                return CreateEscapedText(escapeStrategy.Unescape(trimmedText));
            }
            return CreateNormalText(text);
        }

        private static bool IsQutoed(string text)
        {
            if (text.StartsWith("'") && text.EndsWith("'"))
            {
                return true;
            }
            return text.StartsWith("\"") && text.EndsWith("\"");
        }

        public virtual IText CreateEscapedText(string escapedText)
        {
            return new Text(escapedText, true);
        }

        public virtual IText CreateNormalText(string text)
        {
            return new Text(text, false);
        }
    }
}